//添加房屋表单页面
import 'package:dio/dio.dart';
import 'package:enjoy_plus_hm/utils/eventBus.dart';
import 'package:enjoy_plus_hm/utils/request.dart';
import 'package:enjoy_plus_hm/utils/toast.dart';
import 'package:enjoy_plus_hm/utils/validate.dart';
import 'package:flutter/material.dart';
// import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:image_picker/image_picker.dart';

class HouseForm extends StatefulWidget {
  HouseForm({super.key, this.point, this.building, this.room, this.editForm});
  //小区信息
  String? point;
  //楼栋信息
  String? building;
  //房间号信息
  String? room;

  Map? editForm;

  @override
  State<HouseForm> createState() => _HouseFormState();
}

class _HouseFormState extends State<HouseForm> {
  //表单信息
  Map _formData = {
    // 'id': '', //id
    'point': '', //小区信息
    'building': '', //楼栋信息
    'room': '', //房间号信息
    'name': '', //业主姓名
    'gender': 0, //性别,默认选中女
    'mobile': '', //手机号
    'idcardFrontUrl': '', //身份证正面
    'idcardBackUrl': '', //身份证反面
  };
  //给表单绑定控制器
  //姓名
  final TextEditingController _nameController = TextEditingController();
  //手机号
  final TextEditingController _mobileController = TextEditingController();

  //获取传递的小区,楼栋,房间号
  @override
  void initState() {
    super.initState();
    setState(() {
      //编辑
      if (widget.editForm != null) {
        _formData = widget.editForm!;
        //回显姓名和手机号
        _nameController.text = _formData['name'];
        _mobileController.text = _formData['mobile'];
      } else {
        //新增
        _formData['point'] = widget.point;
        _formData['building'] = widget.building;
        _formData['room'] = widget.room;
      }
    });
  }

  //提交审核
  onsubmit() async {
    setState(() {
      _formData['name'] = _nameController.text;
      _formData['mobile'] = _mobileController.text;
    });
    if (!ValidateUtil.isMobile(_mobileController.text)) return;
    if (!ValidateUtil.isName(_nameController.text)) return;
    if (!ValidateUtil.isIdcard(
      _formData['idcardFrontUrl'],
      _formData['idcardBackUrl'],
    )) {
      return;
    }
    try {
      //由于接口限制传参不能多传,因此需要删除掉status字段
      if (_formData.containsKey('status')) {
        _formData.remove('status');
      }
      final res = await http.post('/room', data: _formData);
      print(res);
      if (res['code'] != 10000) return ToastUtil.showError(res['message']);
      ToastUtil.showInfo('提交成功');
      //popUntil回退路由  回退到house_list页面
      Navigator.popUntil(context, (route) {
        return route.settings.name == '/house_list';
        // return route.settings.name == '/room_list';
      });
      event.fire(DeleteHouseEvent());
    } catch (e) {
      ToastUtil.showError(e.toString());
    }
  }

  //身份证默认添加的组件 tag:是正面还是反面,info正面和反面的中间文字文案
  Widget _builderAddCardPhoto(String tag, String info) {
    return GestureDetector(
      onTap: () {
        showBottomSheet(tag);
      },
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          const Icon(Icons.add,
              size: 30, color: Color.fromARGB(255, 82, 145, 175)),
          Text(
            info,
            style: const TextStyle(color: Color.fromARGB(255, 85, 145, 175)),
          ),
        ],
      ),
    );
  }

  //添加图片后的组件
  Widget _buildIdcardPhoto(String tag, String imgUrl) {
    return Stack(
      children: [
        //图片
        Image.network(
          imgUrl,
          width: MediaQuery.of(context).size.width,
          fit: BoxFit.contain,
        ),
        //右上角删除icon
        Positioned(
          top: 0,
          right: 0,
          child: GestureDetector(
            onTap: () {
              setState(() {
                _formData[tag] = '';
              });
            },
            child: const Icon(Icons.delete, size: 20, color: Colors.red),
          ),
        ),
      ],
    );
  }

  //相机  or  相册半模态弹窗
  showBottomSheet(String tag) {
    showModalBottomSheet(
      context: context,
      builder: (context) {
        return SizedBox(
          height: 200,
          child: Column(
            children: [
              ListTile(
                leading: const Icon(Icons.camera_alt),
                title: const Text('拍照'),
                trailing: const Icon(Icons.arrow_forward_ios_rounded),
                onTap: () async {
                  final ImagePicker picker = ImagePicker();
                  //拍照
                  final XFile? photo = await picker.pickImage(
                    source: ImageSource.camera,
                  );
                  if (photo != null) {
                    //获取路径(沙箱中的)
                    // print(photo.path);
                    // uploadAvator(photo.path);
                    uploadAvator(tag, photo.path);
                  }
                },
              ),
              ListTile(
                leading: const Icon(Icons.photo),
                title: const Text('相册'),
                trailing: const Icon(Icons.arrow_forward_ios_rounded),
                onTap: () async {
                  final ImagePicker picker = ImagePicker();
                  //相册
                  final XFile? image = await picker.pickImage(
                    source: ImageSource.gallery,
                  );
                  if (image != null) {
                    //获取路径(沙箱中的)
                    // print(image.path);
                    // uploadAvator(image.path);
                    uploadAvator(tag, image.path);
                  }
                },
              ),
            ],
          ),
        );
      },
    );
  }

  //上传图片
  uploadAvator(String tag, String imagePath) async {
    print(imagePath);
    try {
      //压缩图片
      // 1. 直接创建临时压缩文件
      // final compressedBytes = await FlutterImageCompress.compressWithFile(
      //   imagePath,
      //   quality: 70, // 70%质量压缩
      //   // minHeight: 800, // 最大高度800px
      //   // minWidth: 800, // 最大宽度800px
      //   autoCorrectionAngle: true,
      // );
      // if (compressedBytes == null) return ToastUtil.showError('图片压缩失败');

      //第一步:创建FormData
      // FormData fd = FormData.fromMap({
      //   'file': MultipartFile.fromBytes(
      //     compressedBytes,
      //     filename: 'avatar.jpg',
      //   ),
      // });

      FormData fd = FormData.fromMap({
        //接口需要的数据
        'file': await MultipartFile.fromFile(
          imagePath,
        ), //MultipartFile转换文件,同时是异步的操作
        'type': 'avatar',
      });
      //第二步:发送请求
      final res = await http.post('/upload', data: fd);
      print(res);
      if (res['code'] != 10000) return ToastUtil.showError('上传失败');
      setState(() {
        _formData[tag] = res['data']['url'];
        ToastUtil.showSuccess('上传成功');
      });
    } catch (e) {
      return ToastUtil.showError('上传失败');
    } finally {
      Navigator.pop(context);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // 设置导航条
      appBar: AppBar(
        title: Text('${_formData.containsKey('id') ? '编辑' : '添加'}房屋信息'),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      // 设置主体内容
      body: Container(
        padding: const EdgeInsets.all(10),
        child: Stack(
          alignment: Alignment.bottomCenter,
          children: [
            //上方用listview
            Container(
              margin: const EdgeInsets.only(bottom: 80),
              child: ListView(
                children: [
                  //第一行房屋信息文案
                  const Text(
                    '房屋信息',
                    style: TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.bold,
                      color: Colors.grey,
                    ),
                  ),
                  const SizedBox(height: 10),
                  //第二行房屋信息,前面页面带过来的小区,楼栋和房间号信息
                  Container(
                    width: MediaQuery.of(context).size.width,
                    color: Colors.white,
                    padding: const EdgeInsets.all(10),
                    child: Text(
                      '${_formData['point']}${_formData['building']}${_formData['room']}室',
                    ),
                  ),
                  const SizedBox(height: 10),
                  //第三行:业主信息文案
                  const Text(
                    '业主信息',
                    style: TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.bold,
                      color: Colors.grey,
                    ),
                  ),
                  const SizedBox(height: 10),
                  //第四行,业主信息 姓名 or 性别 or 手机号
                  Container(
                    padding: const EdgeInsets.all(10),
                    color: Colors.white,
                    // height: 200,
                    child: Column(
                      children: [
                        //姓名行
                        TextField(
                          controller: _nameController,
                          maxLength: 15,
                          decoration: const InputDecoration(
                            labelText: '姓名',
                            hintText: '请输入姓名',
                            hintStyle: TextStyle(color: Colors.grey),
                            // border: InputBorder.none,
                          ),
                        ),
                        //性别行
                        Row(
                          children: [
                            const Text('性别', style: TextStyle(fontSize: 16)),
                            Radio(
                              value: 0,
                              groupValue: _formData['gender'],
                              onChanged: (value) {
                                // print(value);
                                setState(() {
                                  _formData['gender'] = value;
                                });
                              },
                            ),
                            const Text('女'),
                            Radio(
                              value: 1,
                              groupValue: _formData['gender'],
                              onChanged: (value) {
                                // print(value);
                                setState(() {
                                  _formData['gender'] = value;
                                });
                              },
                            ),
                            const Text('男'),
                          ],
                        ),

                        //手机号
                        TextField(
                          controller: _mobileController,
                          maxLength: 11,
                          keyboardType: TextInputType.phone,
                          decoration: const InputDecoration(
                            labelText: '手机号',
                            hintText: '请输入手机号',
                            hintStyle: TextStyle(color: Colors.grey),
                          ),
                        ),
                      ],
                    ),
                  ),
                  const SizedBox(height: 10),
                  //第五行,添加正面身份证照片文案
                  const Text(
                    '本人身份证照片',
                    style: TextStyle(fontSize: 14, color: Colors.grey),
                  ),
                  const Text(
                    '请拍摄证件原件，并使图片中证件边缘完整，文字清晰，光线均匀',
                    style: TextStyle(fontSize: 10, color: Colors.grey),
                  ),
                  const SizedBox(height: 10),
                  //身份证正面照片的框框  组件
                  Container(
                    color: Colors.white,
                    height: 400,
                    child:
                        // Text('+')
                        //idcardFrontUrl表示正面,idcardBackUrl表示背面
                        _formData['idcardFrontUrl'] == ''
                            ? _builderAddCardPhoto('idcardFrontUrl', '上传人像面照片')
                            : _buildIdcardPhoto(
                                'idcardFrontUrl',
                                _formData['idcardFrontUrl'],
                              ),
                  ),
                  const SizedBox(height: 10),
                  //身份证反面照片的框框  组件
                  Container(
                    color: Colors.white,
                    height: 400,
                    child: _formData['idcardBackUrl'] == ''
                        ? _builderAddCardPhoto('idcardBackUrl', '上传国徽面照片')
                        : _buildIdcardPhoto(
                            'idcardBackUrl',
                            _formData['idcardBackUrl'],
                          ),
                  ),
                ],
              ),
            ),
            //底部是一个按钮
            Container(
              // color: Colors.white,
              width: MediaQuery.of(context).size.width,
              height: 80,
              padding: const EdgeInsets.all(10),
              child: ElevatedButton(
                onPressed: () {
                  onsubmit();
                },
                child: const Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(Icons.exit_to_app, size: 20),
                    Text('提交审核', style: TextStyle(color: Colors.purple)),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
